﻿#region LICENSE
/*
Copyright 2010, Iain Sproat
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

 * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
 * The names of the contributors may not be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */
#endregion
 	
using System;
using System.Xml;
using System.Xml.Schema;
using System.Globalization;
using System.Collections.Generic;
using System.IO;

using log4net;

namespace IfcDotNet.XmlSerializer
{
    /// <summary>
    /// IfcXmlValidator validates xml which claim to be IfcXml compatible
    /// against the IFC xml schemas.
    /// </summary>
    public class IfcXmlValidator
    {
        /// <summary>
        /// logger
        /// </summary>
        private readonly ILog logger = LogManager.GetLogger( typeof( IfcXmlValidator ) );
        
        /// <summary>
        /// warnings generated by the validator
        /// </summary>
        private readonly IList<String> warnings = new List<String>();
        
        /// <summary>
        /// The reader which carries out the validation
        /// </summary>
        XmlReader reader;
        
        /// <summary>
        /// default is true, changed to false if a warning is encountered by the reader
        /// </summary>
        private bool _isValid = true;
        
        /// <summary>
        /// This should be called after the reader has read the entire xml.
        /// True if the passed xml was valid IfcXml.  False if any issues were encountered.
        /// </summary>
        public bool IsValid{
            get{ if(!ReaderIsClosed)
                    this.Validate();
                return this._isValid; }
        }
        
        /// <summary>
        /// The reader which carries out the validation.
        /// 
        /// </summary>
        public XmlReader Reader{
            get{ return this.reader; }
        }
        
        /// <summary>
        /// Warning messages that are thrown by the validator.
        /// </summary>
        public IList<string> Messages{
            get{ return this.warnings; }
        }
        
        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="validateThis"></param>
        public IfcXmlValidator( string validateThis ) : this(new StringReader( validateThis ))
        {
            if(string.IsNullOrEmpty( validateThis ) )
                throw new ArgumentNullException("validateThis");
        }
        
        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="validateThis"></param>
        public IfcXmlValidator( TextReader validateThis ){
            if( validateThis == null )
                throw new ArgumentNullException("validateThis");
            this.CreateValidatingReader( validateThis );
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private void Validate()
        {
            if(ReaderIsClosed)
                return;
            
            _isValid = true;
            
            // Parse the file.
            try{
                while (Reader.Read());
            }catch(XmlException xe){
                logger.Error( xe.Message );
            }catch(InvalidOperationException ioe){
                logger.Error( ioe.Message );
            }finally{
                Reader.Close();
            }
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="validateThis"></param>
        private void CreateValidatingReader(TextReader validateThis){
            if( validateThis == null )
                throw new ArgumentNullException( "validateThis" );
            
            // Create the XmlSchemaSet class.
            XmlSchemaSet sc = new XmlSchemaSet();

            // Add the schema to the collection.
            sc.Add(@"urn:iso.org:standard:10303:part(28):version(2):xmlschema:common", "./schema/ex.xsd");
            sc.Add(@"http://www.iai-tech.org/ifcXML/IFC2x3/FINAL","./schema/IFC2X3.xsd");
            

            // Set the validation settings.
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas = sc;
            settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
            
            // Create the XmlReader object.
            this.reader = XmlReader.Create(validateThis, settings);
        }

        /// <summary>
        /// Log any validation errors
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidationCallBack(object sender, ValidationEventArgs e) {
            _isValid = false;
            string warning = String.Format(CultureInfo.InvariantCulture, "Validation Error: {0}", e.Message);
            warnings.Add( warning );
            logger.Info( warning, e.Exception);
        }
        
        /// <summary>
        /// 
        /// </summary>
        private bool ReaderIsClosed{
            get{
                if(this.reader == null )
                    throw new NullReferenceException("IfcXmlValidator.XmlReader is null, have you correctly constructed the object?");
                return Reader.ReadState == ReadState.Closed;
            }
        }
    }
}
